<?php
/**
 * Copyright (c) 2006-2007, Julien PORTALIER
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright    Copyright (c) 2006-2007, Julien PORTALIER
 * @link         http://featherphp.googlecode.com/
 * @license      http://www.opensource.org/licenses/mit-license.php The MIT License
 */

require APP.'config'.DS.'inflections.php';

/**
 * Singularizes, pluralizes, CamelCases, etc. strings.
 */
class Inflector extends Inflections
{
	static protected $trans;
	
	/**
	 * Transforms to CamelText (eg: BlogComment).
	 */
	static function camelize($str)
	{
		return str_replace(' ', '', ucwords(str_replace('_', ' ', $str)));
	}
	
	/**
	 * Transforms to underscore_text (eg: blog_comment).
	 */
	static function underscore($str)
	{
		return str_replace(' ', '_', strtolower(preg_replace('/(?<=\w)([A-Z])/', ' \1', $str)));
	}
	
	/**
	 * Transforms to table name (eg: blog_comments).
	 */
	static function tableize($str)
	{
		return self::underscore(self::pluralize($str));
	}
	
	/**
	 * Transforms to class name (eg: BlogComment).
	 */
	static function classify($str)
	{
		return self::camelize(self::singularize($str));
	}
	
	/**
	 * @deprecated ?
	 */
	static function humanize($str)
	{
		return str_replace('_', ' ', $str);
	}
	
	/**
	 * Transforms to camelBacked style (eg: blogComment).
	 */
	static function variablize($str)
	{
		$str    = self::camelize($str);
		$str{0} = strtolower($str{0});
		return $str;
	}
	
	/**
	 * Singularizes a word.
	 */
	static function singularize($str)
	{
		if (in_array(strtolower($str), self::$constants))
			return $str;
		foreach(self::$singularize_rules as $rule => $value)
		{
			if (preg_match($rule, $str))
				return preg_replace($rule, $value, $str);
		}
		return $str;
	}
	
	/**
	 * Pluralizes a word.
	 */
	static function pluralize($str)
	{
		if (in_array(strtolower($str), self::$constants))
			return $str;
		foreach(self::$pluralize_rules as $rule => $value)
		{
			if (preg_match($rule, $str))
				return preg_replace($rule, $value, $str);
		}
		return $str;
	}
	
	/**
	 * Transforms text to URL style.
	 * 
	 * Changes spaces and non ascii chars to a dash (but
	 * should preserve accented characters).
	 * 
	 * "This is a title" -> "this-is-a-title"
	 */
	static function slug($str, $strtolower=true)
	{
		if ($strtolower)
			$str = mb_strtolower($str);
		
		# incompatible with unicode strings (?):
#		$str = preg_replace('/[^\d\w]+/u','-', $str);
		
		# hack so accented characters are not removed:
		$str = htmlentities($str, ENT_NOQUOTES, Core::charset);
		$str = preg_replace(array('{([^\d\w\.&;]+|&(lt|gt|amp|nbsp);)}', '{[-]+}'), '-', $str);
		$str = html_entity_decode($str, ENT_NOQUOTES, Core::charset);
		
		# Removes trailing and leading dashes
		return trim($str, '-.&;');
	}
}
?>